
//
//  BorrowOutConpousVC.m
//  BrushFace
//
//  Created by timer_q on 16/1/20.
//  Copyright © 2016年 Zzz. All rights reserved.
//

#import "BorrowOutConpousVC.h"
#import "BorrowOutCouponsCell.h"
#import "FinanceReqModel.h"
#import "NavHelper.h"


@interface BorrowOutConpousVC ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_tableView;
    UILabel *_manyCouponsLabel;
    UIButton *_statuBtn;
    UIButton *_headerBtn;
    NSMutableArray *_dataArray;
}
@property (nonatomic,strong)FinanceReqModel *reqmodel;
@end

@implementation BorrowOutConpousVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navBar setTitle:@"优惠券"];
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_BLUE];
    UIButton *button  = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 100, 44)];
    [button setTitle:@"使用说明" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(rightButtonClick) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.navBar setRightView:button];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self dataInit];
    [self UIConfig];
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - customMethods
- (void)dataInit{
    _dataArray = [[NSMutableArray alloc] init];
    _reqmodel = [FinanceReqModel SceneModel];
    [_reqmodel hope_getBorrowCouponsListAndCB:^(id output) {
#pragma mark-----xuxuejiao
        //优惠券页面，取到数组的元素个数，作为优惠券的张数
        
        NSArray *array = [output objectForKey:@"data"];
        _manyCouponsLabel.text = [NSString stringWithFormat:@"共%lu张可用",array.count];
        
#pragma mark----------------------
        [_dataArray addObjectsFromArray:[output objectForKey:@"data"]];
        [_tableView reloadData];
    }];
}
- (void)UIConfig{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView.tableHeaderView = [self headerView];
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
}

- (UIView *)headerView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    view.backgroundColor = [UIColor clearColor];
    
    _manyCouponsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 30)];
    _manyCouponsLabel.textAlignment = NSTextAlignmentCenter;
    _manyCouponsLabel.textColor = [UIColor grayColor];
    _manyCouponsLabel.text = @"共5张可用";
    [view addSubview:_manyCouponsLabel];
    UIView *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 39, SCREEN_WIDTH, 1)];
    label.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
    [view addSubview:label];
    return view;
}
#pragma mark - tableViewdelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BorrowOutCouponsCell *cell = [BorrowOutCouponsCell loadBundleNib];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *subDict = [_dataArray objectAtIndex:indexPath.row];
    cell.couponsTitle.text = subDict[@"name"];
    NSString *limitstr = subDict[@"limitstr"];
    cell.couponsMoney.text = [NSString stringWithFormat:@"¥%@",[subDict objectForKey:@"couponsvalue"]];
    NSString *finalStr = [limitstr stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
    cell.couponsLimit.text = finalStr;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    
    _statuBtn = [[UIButton alloc] initWithFrame:CGRectMake(12, 17.5, 15, 15  )];
    [_statuBtn setBackgroundImage:[UIImage imageNamed:@"chujieyouhuiquandefault"] forState:UIControlStateNormal];
    [_statuBtn setBackgroundImage:[UIImage imageNamed:@"chujieyouhuiquanselect"] forState:UIControlStateSelected];
    _statuBtn.selected = YES;
    [view addSubview:_statuBtn];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 16, SCREEN_WIDTH-40, 18)];
    label.text = @"不使用优惠券";
    label.textColor = [UIColor lightGrayColor];
    [view addSubview:label];
    view.userInteractionEnabled = YES;
    _headerBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    [_headerBtn addTarget:self action:@selector(headerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_headerBtn];
    
    return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dict = [_dataArray objectAtIndex:indexPath.row];
    NSString *jsStr = [dict objectForKey:@"couponslimit"];
    jsStr = [jsStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    jsStr = [jsStr stringByReplacingOccurrencesOfString:@"(function()" withString:@"function couponslimit(innertype,faceup,face,isface,balance,interest,priod,amount,days)"];
    jsStr = [jsStr stringByReplacingOccurrencesOfString:@")()" withString:@""];
    JSContext *context = [[JSContext alloc] init];
    [context evaluateScript:jsStr];
    JSValue *couponslimit = context[@"couponslimit"];
    
    int day = [self.days intValue]+[self.priod intValue]*30;
    JSValue *sum = [couponslimit callWithArguments:@[[dict objectForKey:@"innertype"], self.faceup,self.face,self.isface,self.balance,self.interest,self.priod,self.amount,[NSString stringWithFormat:@"%d",day]]];
    NSString *ret = [sum toString];
    
    if(![ret isEqualToString:@"null"]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:ret delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    NSString *ruleJS = [dict objectForKey:@"rule"];
    ruleJS = [ruleJS stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    ruleJS = [ruleJS stringByReplacingOccurrencesOfString:@"(function()" withString:@"function rule(innertype,faceup,face,isface,balance,interest,priod,amount,days)"];
    ruleJS = [ruleJS stringByReplacingOccurrencesOfString:@")()" withString:@""];
    [_tableView reloadData];
    BorrowOutCouponsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.statuBtn.selected = YES;
    _statuBtn.selected = NO;
    
    [self.delegate conpousId:[dict objectForKey:@"id"] andJSCouponslimit:jsStr andRuleJS:ruleJS andConpousType:[NSString stringWithFormat:@"%@",[dict objectForKey:@"innertype"]]];
    [self performSelector:@selector(chooseConpous) withObject:nil afterDelay:0.5];
}
- (void)chooseConpous{

[self.navigationController popViewControllerAnimated:YES];
}
- (void)backToRootVC{
    [self.delegate nullConpous:_dataArray.count];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)headerBtnClick{
    [_tableView reloadData];
    _statuBtn.selected = YES;
    [self performSelector:@selector(backToRootVC) withObject:nil afterDelay:0.5];
}
- (void)rightButtonClick{
    [NavHelper gotoInstructionsWithConpousVC];
}
@end
